package com.xckj.cycling.utils

import android.Manifest
import com.xckj.cycling.context.AppContext.Companion.globalContext
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.view.View
import android.webkit.JavascriptInterface
import androidx.health.connect.client.HealthConnectClient
import androidx.lifecycle.lifecycleScope
import com.xckj.cycling.framework.lazyGlobalViewModel
import com.junca.android.service.Request
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.language.LanguageConfig
import com.tbruyelle.rxpermissions3.RxPermissions
import com.xckj.cycling.activity.*
import com.xckj.cycling.context.AppContext
import com.xckj.cycling.framework.BaseActivityKt
import com.xckj.cycling.global.Constant
import com.xckj.cycling.repository.FileRepository
import org.json.JSONObject
import com.xckj.cycling.view.CWebView
import com.xckj.cycling.viewmodel.LoginViewModel
import com.xckj.cycling.viewmodel.MapViewModel
import com.xckj.cycling.viewmodel.RouteLineViewModel
import kotlinx.coroutines.launch
import org.json.JSONException

/**
 * 这里定于于H5 的js 交互
 * loadUserInfo   语言和token
chooseCars   选择车辆    ios参数 {id:'12'}   安卓直接传的id
addCarsclick   添加车辆
clearHistory  清理缓存
userInfoEdit  修改用户信息后的触发方法
startEditHead  改变图像的方法
getTopHeight  获取顶部栏高度
onBackPress  返回按钮
1.语言切换  之前是原生的 现在变成h5了 需不需要暴漏一个方法  来传给你当前语言的状态。ios  getLangues({lang:'zh   或  en'})   anzhuo   getLangues(zh)
2.   链接服务里面  需要你们暴漏一个方法 用来打开 谷歌健康 （苹果健康） 的方法  getHealthServe
3. 健康见解  连接设备 方法  getManagementLink
 */
class JsAction(private val activity: BaseActivityKt, private val webView: CWebView) {
    //1.语言切换  之前是原生的 现在变成h5了 需不需要暴漏一个方法  来传给你当前语言的状态。ios  getLangues({lang:'zh   或  en'})   anzhuo   getLangues(zh)
    //2.   链接服务里面  需要你们暴漏一个方法 用来打开 谷歌健康 （苹果健康） 的方法  getHealthServe
    //3. 健康见解  连接设备 方法  getManagementLink
    //4.  设置   自行车   点击  toDeviceLink
    private val deliver = Handler(Looper.getMainLooper())
    private val routeLineViewModel: RouteLineViewModel by lazyGlobalViewModel()
    protected val viewModel: MapViewModel by lazyGlobalViewModel()

    @JavascriptInterface
    fun login() {
        deliver.post {
            //跳到登录注册页面
//                if (callback != null) {
//                    if (!SpUserTable.getInstance().getGuideState()) {
//                        callback.jsRegisterCallBack();
//                    }
//                }
        }
    }

    @JavascriptInterface
    fun register() {
        deliver.post {
            //跳到登录注册页面
//                if (callback != null) {
//                    if (!SpUserTable.getInstance().getGuideState()) {
//                        callback.jsRegisterCallBack();
//                    }
//                }
        }
    }

    //同步用户信息接口
    @JavascriptInterface
    fun islogin(): String {
//        //返回参数,登录状态、手机号、userid、个人信息、身份（律师/委托人）
//        String userid = SpUserTable.getInstance().getUserId();
//        String phone = SpUserTable.getInstance().getUserName();
//        String realname = SpUserTable.getInstance().getRealName();
//        String token = SpUserTable.getInstance().getTooken();
//        boolean islogin = false;
//        String titleTag = SpUserTable.getInstance().getTitleTag();
//        if (!TextUtils.isEmpty(userid)) {
//            islogin = true;
//        }
//
//        //生日
//        String birthday = SpUserTable.getInstance().getBirthday();
//
//        //语言
//        String languageid = SpUserTable.getInstance().getLanguageId();
//        String languagename = SpUserTable.getInstance().getLanguageName();
//
//        // version 版本
//        int code = AppUtils.getAppVersionCode();
//        String vname = AppUtils.getAppVersionName();
//        String version = vname + "." + code;
//
//        JSONObject jsonObject = new JSONObject();
//        try {
//            jsonObject.put("userid", userid);
//            jsonObject.put("phone", phone);
//            jsonObject.put("realname", realname);
//            jsonObject.put("islogin", islogin);
//            jsonObject.put("token", token);
//            jsonObject.put("version", version);
//
//            //
//            jsonObject.put("birthday", birthday);
//            jsonObject.put("languageids", languageid);
//            jsonObject.put("languagestrings", languagename);
//
//            //
//            JSONObject titleobj = new JSONObject();
//            if (titleTag.equals("0")) {
//                titleobj.put("identity", "律师");
//                titleobj.put("tag", "0");
//            } else if (titleTag.equals("1")) {
//                titleobj.put("identity", "委托人");
//                titleobj.put("tag", "1");
//            } else {
//                titleobj.put("identity", "");
//                titleobj.put("tag", "-1");
//            }
//            jsonObject.put("title", titleobj);
//
//            //
//            String userinfo = SpUserTable.getInstance().getUserInfo();
//            JSONObject infoObj = JSON.parseObject(userinfo);
//            jsonObject.put("info", infoObj);
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return jsonObject.toString();
        return ""
    }

    /**
     * H5 里点击了返回
     */
    @JavascriptInterface
    fun onBackPress() {
        deliver.post {
            activity.onBackPressed()
        }
    }

    /**
     * 启动换头像
     */
    @JavascriptInterface
    fun startEditHead() {
        activity.startActivity(Intent(activity, EditHeadActivity::class.java))
    }

    @JavascriptInterface
    fun loadUserInfo(): String {
        val jsonObject = JSONObject()
        try {
            jsonObject.put("token", SpUtil.getString(globalContext(), Constant.TOKEN))
            jsonObject.put("lang", LanguageUtils.getLanguage())
        } catch (e: JSONException) {
            e.printStackTrace()
        }
        return jsonObject.toString()
    }

    @get:JavascriptInterface
    val token: String
        get() = SpUtil.getString(globalContext(), Constant.TOKEN)

    @JavascriptInterface
    fun getTopHeight(): String {
        return StatusBarHelper.getStatusbarHeightInDp().toString().let {
            JSONObject().apply {
                put("height", it)
            }.toString()
        }
    }

    /**
     * H5 设置语言
     */
    @JavascriptInterface
    fun getLangues(lan: String?) {
        deliver.post {
            LanguageUtils.setCurrentLanguage(lan)
            AppContext.globalContext().updateLanguage()
            activity.startActivity(
                Intent(
                    activity,
                    SplashActivity::class.java
                ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
            )
        }
    }


    @JavascriptInterface
    fun loginOut() {
        deliver.post {
            SpUtil.put(AppContext.globalContext(), Constant.TOKEN, "")
            activity.startActivity(
                Intent(
                    activity,
                    SplashActivity::class.java
                ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_CLEAR_TASK)
            )
        }
    }

    private val loginViewModel: LoginViewModel by lazyGlobalViewModel()

    @JavascriptInterface
    fun userInfoEdit() {
        deliver.post {
            loginViewModel.loadUserCenter()
        }
    }


    @JavascriptInterface
    fun addCarsclick() {
        deliver.post {
            activity.startActivity(
                Intent(
                    activity,
                    AddDeviceActivity::class.java
                )
            )
        }
    }

    @JavascriptInterface
    fun getHealthServe(): String {
        val hasClient =
            HealthConnectClient.sdkStatus(AppContext.globalContext()) == HealthConnectClient.SDK_AVAILABLE
        deliver.post {
            activity.startActivity(Intent(activity, HealthDelegateActivity::class.java))
        }
        return if (hasClient) {

            JSONObject().let {
                it.put("openHealth", true)
                it.toString()
            }
        } else {
            JSONObject().let {
                it.put("openHealth", false)
                it.toString()
            }
        }

    }

    private val mapViewModel: MapViewModel by lazyGlobalViewModel()

    /**
     * 返回当前的经纬度
     */
    @JavascriptInterface
    fun location(): String {
        val last = mapViewModel.lastRecordPoint
        if (last == null) {
            deliver.post {
                RxPermissions(activity).requestEachCombined(
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION
                )
                    .subscribe {
                        if (it.granted) {
                            mapViewModel.refreshLocation()
                        }
                    }
            }
        }
        return JSONObject().let {
            last?.apply {
                it.put("lat", latitude())
                it.put("lng", longitude())
            }
            it.toString()
        }
    }

    @JavascriptInterface
    fun chooseCars(id: String) {
        loginViewModel.setEid(id)
    }

    @JavascriptInterface
    fun addcarsphoto(id: String) {
        deliver.post {
            PictureSelector.create(activity)
                .openGallery(SelectMimeType.ofImage())
                .setImageEngine(GlideEngine.createGlideEngine())
                .setLanguage(LanguageConfig.ENGLISH)
                .setMaxSelectNum(1)
                .setSelectionMode(SelectModeConfig.SINGLE)
                .forResult(object : OnResultCallbackListener<LocalMedia> {
                    override fun onResult(result: java.util.ArrayList<LocalMedia>?) {
                        result?.firstOrNull()?.let {
                            activity.lifecycleScope.launch {
                                activity.showLoading()
                                val repo = FileRepository()
                                val r = repo.upload(it.realPath)
                                if (r.isSuccessful) {
                                    Request.postSuspend<Any>(
                                        "qixing/equipment/modifyequipmentimg",
                                        HashMap<String, Any>().apply {
                                            put("id", id)
                                            put("img", r.data?.url ?: "")
                                        })
                                }
                                activity.hideDialog()
                                webView.mAgentWeb.urlLoader.reload()
                            }
                        }
                    }

                    override fun onCancel() {

                    }

                })
        }
    }

    @JavascriptInterface
    fun getlocationInfo(): String {
        val location = mapViewModel.lastRecordPoint
        return JSONObject().let {
            it.put("lat", location?.latitude() ?: 0.0)
            it.put("lng", location?.longitude() ?: 0.0)
            it.toString()
        }
    }

    @JavascriptInterface
    fun addRoute(id: String) {
        viewModel.loadNavigationDetailCallBack(id) {
            if (it.isSuccessful) {
                it.data?.detail?.apply {
                    viewModel.navigationDetail.value = it.data
                    activity.startActivity(
                        Intent(activity, EditRouteActivity::class.java)
                    )
                }
            }
        }
    }

    @JavascriptInterface
    fun getNoticeStatus(): String {
        val open = NotificationUtil.isNotificationEnabled(activity);
        return if (open) "1" else "0"
    }

    @JavascriptInterface
    fun changeNotice(): String {
        NotificationUtil.jump(activity)
        val open = NotificationUtil.isNotificationEnabled(activity);
        return if (open) "1" else "0"
    }

    @JavascriptInterface
    fun jsonload() {
        deliver.post {
            webView.progress.visibility = View.GONE
        }
    }

    @JavascriptInterface
    fun showLoading() {
        deliver.post {
            webView.progress.visibility = View.VISIBLE
        }
    }

    @JavascriptInterface
    fun hideLoading() {
        deliver.post {
            webView.progress.visibility = View.GONE
        }
    }

}